package com.mzba.place.fragment;

import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.google.gson.Gson;
import com.mzba.place.R;
import com.mzba.place.adapter.MyArrayAdapter;
import com.mzba.place.entity.ReportEntity;
import com.mzba.place.entity.ReportInfoGson;
import com.mzba.place.ui.MainActivity;
import com.mzba.place.utils.AppContext;
import com.mzba.place.utils.BasicUIEvent;
import com.mzba.place.utils.HttpUtils;
import com.mzba.place.utils.StringUtil;
import com.mzba.place.utils.UICore;
import com.mzba.place.utils.UrlConfig;
import com.mzba.place.utils.Utils;
/**
 * 
 * @author 06peng
 *
 */
public class HomeFragment extends SherlockFragment implements OnClickListener, Callback, BasicUIEvent {
	
	private MainActivity mainActivity;
	private FragmentManager fm;
	public MapFragment mapFragment;
	public ReportListFragment listFragment;
	public Fragment lastFragment;
	
	private ImageButton mapImageBtn;
	private ImageButton listImageBtn;
	
	private Spinner reportTypeSpinner;
	private Spinner reportTimeSpinner;
	private View view;
	
	private MyArrayAdapter reportTypeAdapter;
	private MyArrayAdapter reportTimeAdapter;
	public View filterView;
	public View filterTipsView;
	public int report_type;
	public int report_time;
	
	private final int filter_reports = 1;
	private Handler handler;
	public boolean isLoading;
	
	private boolean firstListClick;
	public boolean firstReportType;
	public boolean firstReportTime;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mainActivity = (MainActivity) getSherlockActivity();
		handler = new Handler(this);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.home_fragment, null);
		mapImageBtn = (ImageButton) view.findViewById(R.id.mapImageButton);
		mapImageBtn.setOnClickListener(this);
		listImageBtn = (ImageButton) view.findViewById(R.id.listImageButton);
		listImageBtn.setOnClickListener(this);
		
		filterView = view.findViewById(R.id.filter_layout);
		filterTipsView = view.findViewById(R.id.home_filter_tips);
		reportTypeSpinner = (Spinner) view.findViewById(R.id.report_type_spinner);
		reportTimeSpinner = (Spinner) view.findViewById(R.id.report_time_spinner);
//		reportTypeAdapter = ArrayAdapter.createFromResource(mainActivity, R.array.reportType, R.layout.spinner_item);
		reportTypeAdapter = new MyArrayAdapter(mainActivity,R.layout.spinner_item);
		reportTypeAdapter.addAll(getResources().getStringArray(R.array.reportType));
		reportTypeAdapter.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
		reportTypeSpinner.setAdapter(reportTypeAdapter);
		
//		reportTimeAdapter = ArrayAdapter.createFromResource(mainActivity, R.array.reportTime, R.layout.spinner_item);
		reportTimeAdapter = new MyArrayAdapter(mainActivity,R.layout.spinner_item);
		reportTimeAdapter.addAll(getResources().getStringArray(R.array.reportTime));
		reportTimeAdapter.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
		reportTimeSpinner.setAdapter(reportTimeAdapter);
		reportTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				report_type = arg2;
				filterView.setVisibility(View.GONE);
				setFilterTips();
				if (firstReportType) {
					System.out.println("+++++++ reportTypeSpinner ++++++++++++");
					UICore.eventTask(HomeFragment.this, mainActivity, filter_reports, null, true);
				}
				firstReportType = true;
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
		});
		reportTimeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				report_time = arg2;
				filterView.setVisibility(View.GONE);
				setFilterTips();
				if (firstReportTime) {
					System.out.println("+++++++ reportTimeSpinner ++++++++++++");
					UICore.eventTask(HomeFragment.this, mainActivity, filter_reports, null, true);
				}
				firstReportTime = true;
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
		});
		reportTypeSpinner.setSelection(report_type);
		reportTypeSpinner.setSelected(true);
		reportTimeSpinner.setSelection(report_time);
		reportTimeSpinner.setSelected(true);
		
		fm = mainActivity.getSupportFragmentManager();
		FragmentTransaction fragmentTransaction = fm.beginTransaction();
		mapFragment = new MapFragment();
		listFragment = new ReportListFragment();
		fragmentTransaction.add(R.id.home_content_id, mapFragment, AppContext.MapFragmentTag);
		fragmentTransaction.add(R.id.home_content_id, listFragment, AppContext.ReportListFragmentTag);
		fragmentTransaction.show(mapFragment);
		fragmentTransaction.hide(listFragment);
		fragmentTransaction.commit();
		lastFragment = mapFragment;
		return view;
	}
	
	private void setFilterTips() {
		if (report_time == 0 && report_type == 0) {
			filterTipsView.setVisibility(View.GONE);
		} else {
			filterTipsView.setVisibility(View.VISIBLE);
			TextView tv_type = (TextView) filterTipsView.findViewById(R.id.filter_tv);
			TextView tv_time = (TextView) filterTipsView.findViewById(R.id.time_tv);
			if (report_type == 0) {
				tv_type.setCompoundDrawablesWithIntrinsicBounds(R.drawable.upload_type_icon, 0, 0, 0);
			} else if (report_type == 1) {
				tv_type.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_map_marker_01, 0, 0, 0);
			} else if (report_type == 2) {
				tv_type.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_map_marker_02, 0, 0, 0);
			} else if (report_type == 3) {
				tv_type.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_map_marker_03, 0, 0, 0);
			} else if (report_type == 4) {
				tv_type.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_map_marker_04, 0, 0, 0);
			} else {
				tv_type.setCompoundDrawablesWithIntrinsicBounds(R.drawable.upload_type_icon, 0, 0, 0);
			}
			tv_type.setText(reportTypeSpinner.getSelectedItem().toString());
			tv_time.setText(reportTimeSpinner.getSelectedItem().toString());
		}
	}
	
	@Override
	public void onResume() {
		super.onResume();
	}
	
	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.mapImageButton) {
			mapImageBtn.setBackgroundResource(R.drawable.tab_map_selected);
			listImageBtn.setBackgroundResource(R.drawable.tab_list_normal);
			if (lastFragment != mapFragment) {
				Fragment currentFragment = fm.findFragmentByTag(AppContext.MapFragmentTag);
				FragmentTransaction fragmentTransaction = fm.beginTransaction();
				if (currentFragment == null) {
					mapFragment = new MapFragment();
					fragmentTransaction.add(R.id.home_content_id, mapFragment, AppContext.MapFragmentTag);
				} 
				currentFragment = mapFragment;
				fragmentTransaction.show(currentFragment);
				if (lastFragment != null) {
					fragmentTransaction.hide(lastFragment);
				}
				fragmentTransaction.commit();
				lastFragment = mapFragment;
				mainActivity.setMapMenu();
			}
		} else if (v.getId() == R.id.listImageButton) {
			mapImageBtn.setBackgroundResource(R.drawable.tab_map_normal);
			listImageBtn.setBackgroundResource(R.drawable.tab_list_selected);
			if (lastFragment != listFragment) {
				Fragment currentFragment = fm.findFragmentByTag(AppContext.ReportListFragmentTag);
				FragmentTransaction fragmentTransaction = fm.beginTransaction();
				if (!firstListClick) {
					listFragment = new ReportListFragment();
					fragmentTransaction.add(R.id.home_content_id, listFragment, AppContext.ReportListFragmentTag);
					firstListClick = true;
				} else {
					if (currentFragment == null) {
						listFragment = new ReportListFragment();
						fragmentTransaction.add(R.id.home_content_id, listFragment, AppContext.ReportListFragmentTag);
					} 
				}
				currentFragment = listFragment;
				fragmentTransaction.show(currentFragment);
				if (lastFragment != null) {
					fragmentTransaction.hide(lastFragment);
				}
				fragmentTransaction.commit();
				lastFragment = listFragment;
				mainActivity.actionBar.setTitle(R.string.fragment_list);
				mainActivity.setListMenu();
			}
		}
	}
	
	/**
	 * 筛选reports
	 * 
	 * @param type 1: 扒窃抢劫 2: 色狼变态 3: 走失拐卖 4: 苹果丢了
	 * @param time 上报信息时间范围，1: 最近3天 2: 最近一周 3: 最近一个月 4: 最近半 年 5: 最近一年
	 */
	public void filterReports() {
		try {
			GeoPoint leftPoint = Utils.getLeftTopPoint(mapFragment.mMapView);
			GeoPoint rightPoint = Utils.getRightBottmPoint(mapFragment.mMapView);
			StringBuilder builder = new StringBuilder();
			builder.append(UrlConfig.reports);
			builder.append("?auth_token=");
			builder.append(AppContext.getInstance().getAuthToken());
			builder.append("&min_y=");
			builder.append(String.valueOf(leftPoint.getLatitudeE6() / 1E6));
			builder.append("&min_x=");
			builder.append(String.valueOf(leftPoint.getLongitudeE6() / 1E6));
			builder.append("&max_y=");
			builder.append(String.valueOf(rightPoint.getLatitudeE6() / 1E6));
			builder.append("&max_x=");
			builder.append(String.valueOf(rightPoint.getLongitudeE6() / 1E6));
			if (report_type != 0) {
				builder.append("&r_type=");
				builder.append(String.valueOf(report_type));
			}
			if (report_time != 0) {
				builder.append("&r_time=");
				builder.append(String.valueOf(report_time));
			}
			String response = HttpUtils.doGet(builder.toString());
			if (StringUtil.isNotBlank(response)) {
				Gson gson = new Gson();
				ReportInfoGson reportGson = gson.fromJson(response, ReportInfoGson.class);
				if (reportGson != null) {
					List<ReportEntity>  reports = reportGson.getReports();
					// 地图和列表用的是同一份数据，所以需要在这里设置
					mainActivity.setReports(reports);
				}
			}
			handler.sendEmptyMessage(filter_reports);
		} catch (Exception e) {
			isLoading = false;
			e.printStackTrace();
			mainActivity.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					mainActivity.setSupportProgressBarIndeterminateVisibility(false);
				}
			});
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case filter_reports:
			isLoading = false;
			if (mainActivity.currentFragment == this) {
				if (mapFragment != null) {
					mapFragment.locateTo();
				}
				if (listFragment != null) {
					listFragment.init();
				}
//				if (lastFragment == mapFragment) {
//					mapFragment.locateTo();
//				} else {
//					listFragment.init();
//				}
			} else {
				mainActivity.setSupportProgressBarIndeterminateVisibility(false);
			}
			break;

		default:
			break;
		}
		return false;
	}

	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case filter_reports:
			isLoading = true;
			filterReports();
			break;

		default:
			break;
		}
	}
	
	public class ReportFilterAdapter extends ArrayAdapter<String> {

		private String[] objects;
		private int textViewResourceId;
		
		public ReportFilterAdapter(Context context, int textViewResourceId, String[] objects) {
			super(context, textViewResourceId, objects);
			this.objects = objects;
			this.textViewResourceId = textViewResourceId;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView view = (TextView) LayoutInflater.from(mainActivity).inflate(textViewResourceId, null);
			view.setText(objects[position]);
			return view;
		}

		@Override
		public View getDropDownView(int position, View convertView, ViewGroup parent) {
			TextView view = (TextView) LayoutInflater.from(mainActivity).inflate(textViewResourceId, null);
			view.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_launcher, 0, 0, 0);
			view.setText(objects[position]);
			return view;
		}
		
	}
	
}
